
tinymce.PluginManager.add('paragraph', function(editor, url){

    editor.ui.registry.addMenuButton('paragraph', {
        tooltip: '插入段落',
        icon: 'comment-add',
        fetch: function(callback) {
            var items = [
                {
                    type: 'menuitem',
                    text: '第一层级:ABC',
                    onAction: function() {
                        editor.insertContent(generateParagraphContent(1, getDefaultTitle(), getIndex("1")));
                    }
                },
                {
                    type: 'menuitem',
                    text: '第二层级:(1)(2)(3)',
                    onAction: function() {
                        editor.insertContent(generateParagraphContent(2, getDefaultTitle(), getIndex("2")));
                    }
                },
                {
                    type: 'menuitem',
                    text: '第三层级:(a)(b)(c)',
                    onAction: function() {
                        editor.insertContent(generateParagraphContent(3, getDefaultTitle(), getIndex("3")));
                    }
                },
                {
                    type: 'menuitem',
                    text: '第四层级:123',
                    onAction: function() {
                        editor.insertContent(generateParagraphContent(4, getDefaultTitle(), getIndex("4")));
                    }
                },
                {
                    type: 'menuitem',
                    text: '第五层级:abc',
                    onAction: function() {
                        editor.insertContent(generateParagraphContent(5, getDefaultTitle(), getIndex("5")));
                    }
                },
            ]
            callback(items)
        }
    });

    editor.on('init', function () {
        const body = editor.contentDocument.body;
        if ($(body).hasClass("view_body")) {
            return;
        }
        body.addEventListener('keydown', function(e) {
            if (e.key === 'Delete') {
                var $node = $(editor.selection.getNode());
                if ($node.hasClass("mce-paragraph")) {
                    refreshAfterParagraphTitle($node, 0);
                }
            }
        }, true);
    });

    editor.on('NodeChange', function () {
        const body = editor.contentDocument.body;
        if ($(body).hasClass("view_body")) {
            return;
        }
        let level = null;
        $(body).children().each((i, obj) => {
            var $obj = $(obj);
            if ($obj.hasClass("mce-paragraph")) {
                level = $obj.attr("data-mce-level");
            } else {
                $obj.removeClass("parent-level-1 parent-level-2 parent-level-3 parent-level-4 parent-level-5")
                if (level) {
                    $obj.addClass("parent-level-"+level);
                }
            }
        });
    });

    /**
     * 获取选中内容作为默认标题
     * @param editor
     */
    const getDefaultTitle = () => {
        return editor.selection.getContent({format :'text'});
    }

    const replaceIndex = (str, level) => {
        if (level === 1) {
            return str.replace(/[A-Z]\./, "");
        } else if (level === 2) {
            return str.replace(/\(\d+\)/, "");
        } else if (level === 3) {
            return str.replace(/\([a-z]\)/, "");
        } else if (level === 4) {
            return str.replace(/\d+\./, "");
        } else if (level === 5) {
            return str.replace(/[a-z]\./, "");
        }
        return str;
    }

    /**
     * 将序号转化为标题号
     * @param index 序号
     * @param level 层级
     * @returns {string} 标题号
     */
    const formatIndex = (index, level) => {
        if (level === 1) {
            return convertNumberToLowerLetter(index - 1) + '.';
        } else if (level === 2) {
            return '(' + index +')';
        } else if (level === 3) {
            return '(' + convertNumberToUpperLetter(index - 1) +')';
        } else if (level === 4) {
            return index +'.';
        } else if (level === 5) {
            return convertNumberToUpperLetter(index - 1) +'.';
        }
        return "";
    }

    /**
     * 数字转小写字母
     * @param index 数字
     * @returns {string} 小写字母
     */
    const convertNumberToLowerLetter = (index) => {
        if (index <= 25) {
            return String.fromCharCode(65 + index); // 将数字转换为大写字母
        } else {
            var quotient = Math.floor(index / 26) - 1;
            var remainder = index % 26;
            return convertNumberToLowerLetter(quotient) + String.fromCharCode(65 + remainder); // 递归计算每一位的字母
        }
    }

    /**
     * 数字转大写字母
     * @param index 数字
     * @returns {string} 大写字母
     */
    const convertNumberToUpperLetter = (index) => {
        if (index <= 25) {
            return String.fromCharCode(97 + index); // 将数字转换为大写字母
        } else {
            var quotient = Math.floor(index / 26) - 1;
            var remainder = index % 26;
            return convertNumberToUpperLetter(quotient) + String.fromCharCode(97 + remainder); // 递归计算每一位的字母
        }
    }

    /**
     * 计算新增的段落的序号
     * @param l
     * @returns {number}
     */
    const getIndex = (l) => {
        var index = 1;
        var closestParagraphNode = getClosestParagraphNode($(editor.selection.getNode()), l);
        if (closestParagraphNode && closestParagraphNode.attr("data-mce-level") === l) {
            index = getParagraphIndex(closestParagraphNode) + 1;
            refreshAfterParagraphTitle(closestParagraphNode, 2);
        } else if (!closestParagraphNode && l === "1") {
            refreshAllParagraphTitle(1);
        }
        return index;
    }

    const getParagraphIndex = ($node) => {
        var $container = $(editor.contentDocument);
        var paragraphs = $container.find(".mce-paragraph");

        var isCount = false;
        var count = 0;
        for(var i = paragraphs.length - 1; i >= 0; i--){
            var paragraph = $(paragraphs[i]);
            if (paragraph.is($node)) {
                isCount = true;
            }
            if (isCount) {
                if (paragraph.attr("data-mce-level") === $node.attr("data-mce-level")) {
                    count++;
                } else {
                    if (parseInt(paragraph.attr("data-mce-level")) <= parseInt($node.attr("data-mce-level"))) {
                        break;
                    }
                }
            }
        }
        return count;
    }

    /**
     * 刷新之后节点的标题序号
     * @param $node
     * @param num
     */
    const refreshAfterParagraphTitle = ($node, num) => {
        var $container = $(editor.contentDocument);
        var paragraphs = $container.find(".mce-paragraph");
        var isCount = false;
        var count = getParagraphIndex($node);
        for(var i = 0; i < paragraphs.length; i++){
            var paragraph = $(paragraphs[i]);
            if (isCount) {
                if (paragraph.attr("data-mce-level") === $node.attr("data-mce-level")) {
                    var title = paragraph.find("span[contenteditable]");
                    var level = parseInt($node.attr("data-mce-level"));
                    title.text(formatIndex(count+num, level) + replaceIndex(title.text(), level));
                    count++;
                } else {
                    if (parseInt(paragraph.attr("data-mce-level")) <= parseInt($node.attr("data-mce-level"))) {
                        break;
                    }
                }
            }
            if (paragraph.is($node)) {
                isCount = true;
            }
        }
    }

    /**
     * 获取节点最近的段落节点
     * @param $node
     * @param l
     * @returns {null|*}
     */
    const getClosestParagraphNode = ($node, l) => {
        if ($node.is("body")) {
            return null;
        }
        var nodes = $node.prevAll();
        var target = null;
        (nodes || []).each((i, node) => {
            if ($(node).hasClass("mce-paragraph")) {
                if (parseInt($(node).attr("data-mce-level")) <= parseInt(l)) {
                    target = $(node);
                    return false;
                }
            }
        });
        if (target) {
            return target;
        }
        return getClosestParagraphNode($node.parent(), l);
    }

    const generateParagraphContent = (level, defaultTitle, defaultIndex)=> {
        var paragraph = '';
        var titleLevel = 'h' + (level + 1); // h2 h3 h4
        var id = Math.uuid().toLowerCase();
        var title = formatIndex(defaultIndex, level) + ' ' + defaultTitle;
        paragraph += '<'+titleLevel+' id="'+id+'" class="mce-paragraph" style="font-family: 宋体;" data-mce-level="' + level + '" contenteditable="false">';
        paragraph += '<span class="mce-paragraph-affix" data-mce-mergetag-affix="">{*</span>';
        paragraph += '<span contenteditable="true">'+title+'</span>';
        paragraph += '<span class="mce-paragraph-affix" data-mce-mergetag-affix="">*}</span>';
        paragraph += '</'+titleLevel+'>';
        return paragraph;
    }

    /**
     * 刷新所有标题序号
     * @param level
     */
    const refreshAllParagraphTitle = (level) => {
        var $container = $(editor.contentDocument);
        var paragraphs = $container.find(".mce-paragraph");
        var count = 2;
        for(var i = 0; i < paragraphs.length; i++){
            var paragraph = $(paragraphs[i]);
            if (paragraph.attr("data-mce-level") === "1") {
                var title = paragraph.find("span[contenteditable]");
                title.text(formatIndex(count, level) + replaceIndex(title.text(), level));
                count++;
            }
        }
    }

    return {
        getMetadata: function () {
          return  {
            name: "paragraph",//插件名称
            url: "http://exampleplugindocsurl.com", //作者网址
          };
        }
    };

})